import React, { useState, useEffect } from 'react';
import {
  Container,
  Typography,
  TextField,
  Button,
  Box,
  Divider,
  Snackbar,
  Alert,
  CircularProgress
} from '@mui/material';
import settingsAPI from '@/apis/settings';

const AdminSettings = () => {
  const [settings, setSettings] = useState({
    websiteName: '',
    websiteDescription: '',
    contactEmail: '',
    allowNewRegistrations: false,
    defaultUserRole: '',
    defaultProductStatus: '',
    lowStockThreshold: 0,
    orderAutoCancelHours: 0,
    allowRefunds: false,
    notifyNewOrders: false,
    notifyLowStock: false,
    themeColor: ''
  });

  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [snackbar, setSnackbar] = useState({
    open: false,
    message: '',
    severity: 'success'
  });

  useEffect(() => {
    fetchSettings();
  }, []);

  const fetchSettings = async () => {
    try {
      setLoading(true);
      const fetchedSettings = await settingsAPI.getAllSettings();
      setSettings(fetchedSettings);
    } catch (error) {
      console.error('获取设置失败:', error);
      setSnackbar({
        open: true,
        message: '获取设置失败，请稍后再试',
        severity: 'error'
      });
    } finally {
      setLoading(false);
    }
  };

  const handleChange = (event) => {
    const { name, value, checked } = event.target;
    setSettings(prevSettings => ({
      ...prevSettings,
      [name]: event.target.type === 'checkbox' ? checked : value
    }));
  };

  const handleSave = async () => {
    try {
      setSaving(true);
      await settingsAPI.updateSettings(settings);
      setSnackbar({
        open: true,
        message: '设置已成功保存',
        severity: 'success'
      });
    } catch (error) {
      console.error('保存设置失败:', error);
      setSnackbar({
        open: true,
        message: '保存设置失败，请稍后再试',
        severity: 'error'
      });
    } finally {
      setSaving(false);
    }
  };

  const handleCloseSnackbar = (event, reason) => {
    if (reason === 'clickaway') {
      return;
    }
    setSnackbar({ ...snackbar, open: false });
  };

  if (loading) {
    return (
      <Container maxWidth="md" sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
        <CircularProgress />
      </Container>
    );
  }

  return (
    <Container maxWidth="md">
      <Typography variant="h4" component="h1" gutterBottom>
        系统设置
      </Typography>
      
      {/* 基本信息设置 */}
      <Box my={4}>
        <Typography variant="h6" gutterBottom>基本信息设置</Typography>
        <TextField
          fullWidth
          margin="normal"
          name="websiteName"
          label="网站名称"
          value={settings.websiteName}
          onChange={handleChange}
        />
        <TextField
          fullWidth
          margin="normal"
          name="websiteDescription"
          label="网站简介"
          multiline
          rows={2}
          value={settings.websiteDescription}
          onChange={handleChange}
        />
        <TextField
          fullWidth
          margin="normal"
          name="contactEmail"
          label="联系邮箱"
          type="email"
          value={settings.contactEmail}
          onChange={handleChange}
        />
      </Box>

      <Divider />

      <Box my={4}>
        <Button 
          variant="contained" 
          color="primary" 
          onClick={handleSave}
          disabled={saving}
        >
          {saving ? '保存中...' : '保存设置'}
        </Button>
      </Box>

      <Snackbar
        open={snackbar.open}
        autoHideDuration={6000}
        onClose={handleCloseSnackbar}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
      >
        <Alert onClose={handleCloseSnackbar} severity={snackbar.severity} sx={{ width: '100%' }}>
          {snackbar.message}
        </Alert>
      </Snackbar>
    </Container>
  );
};

export default AdminSettings;